//
//  DutyGoBackViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/11/24.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "DutyGoBackViewController.h"
#import "DutyMapViewController.h"
#import "DepartPersonListView.h"
#import "SelectOvertimePersonViewController.h"
#import "AddPlanViewController.h"
#import "AddPlanModel.h"
#import "GoOutPlanTableViewCell.h"
#import "GoOutInfoModel.h"
#import "ImageDetailViewController.h"
#import "UserHeadImageModel.h"
#import "MyJobListViewController.h"

#define postOfficialBusinessInfo @"postOfficialBusinessInfo"
#define getBusinessInformationInfo @"getBusinessInformationInfo"//查询公出申请信息
#define postBusinessReportInfo @"postBusinessReportInfo"//公出汇报
#define uploadPicInfo @"uploadPicInfo"//上传图片

@interface DutyGoBackViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSMutableArray *_photoButtonArr;//签退照片Buton
    NSMutableArray *_photoArr;//所拍照片的arr
    UserHeadImageModel *_imageModel;//头像model
}
@property (nonatomic,strong) CustomField *eatTextField;
@property (nonatomic,strong) UILabel *personLabel;//加班人员label
@property (nonatomic,strong) UILabel *addressLabel;//加班地点label
@property (nonatomic,strong) UILabel *addressTitleLabel;//加班地点TitleLabel
@property (nonatomic,strong) UILabel *eatExpenseLabel;//就餐费用label
@property (nonatomic,strong) UILabel *eatExpenseTitleLabel;//就餐费用TitleLabel
@property (nonatomic,strong) NSString *cityName;//城市
@property (nonatomic,strong) NSString *placeX;//纬度
@property (nonatomic,strong) NSString *placeY;//经度
@property (nonatomic,strong) DepartPersonListModel *personListModel;
@property (nonatomic,strong) NSMutableArray *planArr;//行程计划
@property (nonatomic,strong) UITextView *materialTextView;//带出物品输入框
@property (nonatomic,strong) UITextView *remarksTextView;//备注
@property (nonatomic,strong) UILabel *materialTitleLabel;//带出物品titleLabel
@property (nonatomic,strong) UILabel *remarksTitleLabel;//备注titleLabel
@property (nonatomic,strong) UILabel *photoTitleLabel;//拍照titleLabel
@property (nonatomic,strong) GoOutInfoModel *goOutInfoModel;
@property (nonatomic,strong) UIButton *submitButton;
@property (nonatomic,strong) UIView *footView;

@end

@implementation DutyGoBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavaTitle:@"公出汇报"];
    // Do any additional setup after loading the view.
}

#pragma mark -初始化数据
- (void)dataInit{
    self.businessCode=@"GC0009";
    self.planArr=[NSMutableArray new];
    _photoButtonArr=[NSMutableArray new];
    _photoArr=[NSMutableArray new];
    self.addWorkPersonArr=[NSMutableArray new];
    //,@"行程计划 :",@"就餐费用 :",@" 带出物品及资料 :",@" 备注 :"
    _titleArr=@[@"申请人员 :",@"开始时间 :",@"结束时间 :",@"公出人员 :"];
    //,@"",@"  元",@"请输入带出物品和资料~",@"请输入备注~"
    _messageArr=[NSMutableArray arrayWithArray:@[[LZXHelper getUserName],self.beginStr?self.beginStr:@"点击选择",self.endStr?self.endStr:@"点击选择",[LZXHelper getUserName]]];
}

- (void)setRightNavigation:(NSString *)title{
    
}
#pragma mark -重写不用的方法
- (void)getCountdownTimeInfoRequest{

}

#pragma mark — creatView
- (void)creatView{
    //创建列表
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-64) style:UITableViewStylePlain];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    _tableView.bounces=NO;
    //[self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_tableView];
    [self addTableViewFootView];
    
    //    DatePickerView *date=[[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    //    [[[UIApplication sharedApplication].delegate window] addSubview:date];
}

- (void)addTableViewFootView{
    //添加提交button
    _footView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 186)];
    _footView.backgroundColor=[UIColor clearColor];
    
    _photoTitleLabel=[MyControl creatLabelWithFrame:CGRectMake(8, 0, 80, 20) text:@"拍照说明："];
    _photoTitleLabel.textAlignment=NSTextAlignmentCenter;
    _photoTitleLabel.layer.masksToBounds=YES;
    _photoTitleLabel.layer.cornerRadius=5;
    [_footView addSubview:_photoTitleLabel];
    //添加图片
    CGFloat photoButtonWidth=(IPHONE_WIDTH-80*3)/4;//button间隔
    for (int i=0; i<4; i++) {
        UIButton *signButton=[MyControl creatButtonWithFrame:CGRectMake(photoButtonWidth*(i%3+1)+80*(i%3), 28+photoButtonWidth*(i/3)+80*(i/3), 80, 80) target:self sel:@selector(addPhoto:) tag:140+i image:@"AlbumAddBtn@2x" title:nil];
        if (i!=0) {
            signButton.hidden=YES;
        }
        [_footView addSubview:signButton];
        [_photoButtonArr addObject:signButton];
    }
    
    NSArray *title=@[@"确定"];
    CGFloat buttonWidth=(IPHONE_WIDTH-(title.count+1)*10)/title.count;
    _submitButton=[MyControl creatButtonWithFrame:CGRectMake(10,_footView.height-50, buttonWidth, 40) target:self sel:@selector(submitClick:) tag:120 image:nil title:title[0]];
    _submitButton.layer.masksToBounds=YES;
    _submitButton.layer.cornerRadius=5;
    [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _submitButton.backgroundColor=COLOR_MIDBLUE;
    [_footView addSubview:_submitButton];
    _tableView.tableFooterView=_footView;
}

#pragma mark -提交按钮
- (void)submitClick:(UIButton *)button{
    //如果有必选项没填则需提示和标记出来
    if (!self.beginStr) {
        [LZXHelper postMessageWithText:@"公出开始时间不能为空!" View:self.view];
        [self setLabelBorderColorWithLabel:self.beginTitleLabel color:[UIColor redColor]];
        return;
    }else{
        [self setLabelBorderColorWithLabel:self.beginTitleLabel color:[UIColor clearColor]];
    }
    
    if (!self.endStr) {
        [LZXHelper postMessageWithText:@"公出结束时间不能为空!" View:self.view];
        [self setLabelBorderColorWithLabel:self.endTitleLabel color:[UIColor redColor]];
        return;
    }else{
        [self setLabelBorderColorWithLabel:self.endTitleLabel color:[UIColor clearColor]];
    }
    
    
    if (_photoArr.count==0) {
        [LZXHelper postMessageWithText:@"请拍照!" View:self.view];
        [self setLabelBorderColorWithLabel:_photoTitleLabel color:[UIColor redColor]];
        return;
    }else{
        [self setLabelBorderColorWithLabel:self.addressTitleLabel color:[UIColor clearColor]];
    }
    [self uploadPhotoImage];
}

#pragma mark - 拍照按钮点击

- (void)addPhoto:(UIButton *)button{
    [self setLabelBorderColorWithLabel:self.photoTitleLabel color:[UIColor clearColor]];
    //最后一张图片为添加按钮对其进行特殊处理
    if (button.tag-140==_photoArr.count) {
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            [LZXHelper postMessageWithText:@"您的手机还不支持照相功能！" View:self.view];
            return;
        }
        if (_photoArr.count>=3) {
            [LZXHelper postMessageWithText:@"最多只能提交3张照片！" View:self.view];
            return;
        }
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *otherButtonTitle = NSLocalizedString(@"相册", nil);
        //        NSString *otherButtonTitle2 = NSLocalizedString(@"拍照", nil); 不支持拍照
        NSString *otherButtonTitle2 = NSLocalizedString(@"拍照", nil);
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // Create the actions.
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
                                       {
                                           //cancel Button
                                       }];
        __weak DutyGoBackViewController *myWeakSelf=self;
        //相册
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
                                      {
                                          
                                          //          NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
                                          
                                          if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
                                          {
                                              //如果当前
                                              return;
                                          }
                                          UIImagePickerController *imagePickerController=[[UIImagePickerController alloc]init];
                                          imagePickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                                          imagePickerController.delegate = myWeakSelf;
                                          imagePickerController.allowsEditing=YES;
                                          [self presentViewController:imagePickerController animated:NO completion:nil];
                                      }];
        
        //        UIAlertAction *seeBigImgAction = [UIAlertAction actionWithTitle:otherButtonTitle2 style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
        //      {
        //          NSLog(@"here is bigImg Btn");
        ////            if (_photoURL==nil||_photoURL.length==0) {
        ////                return ;
        ////            }
        ////            PhotoImageViewController *photo=[[PhotoImageViewController alloc]init];
        ////            photo.photoImageURL=_photoURL;
        ////            [self.navigationController pushViewController:photo animated:YES];
        //      }];
        
        
        UIAlertAction *otherAction2 = [UIAlertAction actionWithTitle:otherButtonTitle2 style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            //            NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
            if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
                [LZXHelper postMessageWithText:@"您的手机还不支持照相功能！" View:self.view];
            }
            UIImagePickerController *imagePickerController=[[UIImagePickerController alloc]init];
            imagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
            imagePickerController.delegate=myWeakSelf;
            imagePickerController.allowsEditing=YES;
            [self presentViewController:imagePickerController animated:NO completion:nil];
        }];
        
        
        // Add the actions.
        [alertController addAction:otherAction2];
        //[alertController addAction:otherAction2];  不支持拍照
        [alertController addAction:cancelAction];
        [alertController addAction:otherAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
//        UIImagePickerController *imagePickerController=[[UIImagePickerController alloc]init];
//        imagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
//        imagePickerController.delegate=self;
//        imagePickerController.allowsEditing=YES;
//        [self presentViewController:imagePickerController animated:NO completion:nil];
    }else{
        ImageDetailViewController *imageViewController=[ImageDetailViewController new];
        imageViewController.image=_photoArr[button.tag-140];
        [self.navigationController pushViewController:imageViewController animated:YES];
    }
    
}

#pragma mark -相册Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //编辑时调用
    if (!info[@"UIImagePickerControllerEditedImage"])
    {
        return;
    }
    UIImage *image=info[@"UIImagePickerControllerEditedImage"];
    [_photoArr insertObject:image atIndex:0];
    //将拍的图片显示出来
    for (int i=0;i<_photoButtonArr.count;i++) {
        UIButton *photo=_photoButtonArr[i];
        if (i<_photoArr.count) {
            UIImage *image=_photoArr[i];
            [photo setImage:image forState:UIControlStateNormal];
            photo.hidden=NO;
        }else{
            photo.hidden=YES;
        }
        if (i==_photoArr.count) {
            //[photo setImage:[UIImage imageNamed:@"AlbumAddBtn@2x"] forState:UIControlStateNormal];
            photo.hidden=NO;
        }
    }
    CGFloat photoButtonWidth=(IPHONE_WIDTH-80*3)/4;//button间隔
    //因为还有个增加图片的按钮 所以我加1
    if (_photoArr.count+1>3) {
        NSInteger num=0;
        if ((_photoArr.count+1)%3>0) {
            num=(_photoArr.count+1)/3+1;
        }else{
            num=(_photoArr.count+1)/3;
        }
        _footView.height=28+photoButtonWidth*num+80*num+50;
        _submitButton.y=_tableView.tableFooterView.height-50;
        _tableView.tableFooterView=_footView;
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -textViewDelegate
#pragma mark-将textView的提示文字清空
- (void)textViewDidBeginEditing:(UITextView *)textView{
    [self addTapGestureRecognizer];
    if ([textView.text isEqualToString:@"请输入带回物品和资料~"]||[textView.text isEqualToString:@"请输入~"]) {
        textView.textColor=[UIColor blackColor];
        textView.text=@"";
        //将标记取消
        [self setLabelBorderColorWithLabel:self.materialTitleLabel color:[UIColor clearColor]];
        [self setLabelBorderColorWithLabel:self.remarksTitleLabel color:[UIColor clearColor]];
    }
    NSIndexPath* path = [NSIndexPath indexPathForRow:textView.tag%1000 inSection:textView.tag/1000-1];
    [self performSelector:@selector(scrollToCell:) withObject:path afterDelay:0];
}

#pragma mark-将textView默认文字设置为提示文字
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    [self removeTapGestureRecognizer];
    if (textView.text.length==0) {
        if (textView.tag==3001){
            textView.textColor=[UIColor lightGrayColor];
            textView.text=@"请输入带回物品和资料~";
        }else{
            textView.textColor=[UIColor lightGrayColor];
            textView.text=@"请输入~";
        }
        
    }
    return YES;
}

//#pragma mark -避免键盘遮挡
//- (void)textViewDidBeginEditing:(UITextView *)textView{
//    [self setLabelBorderColorWithLabel:self.reasonTitleLabel color:[UIColor clearColor]];
//    NSIndexPath* path = [NSIndexPath indexPathForRow:textView.tag-200 inSection:0];
//    [self performSelector:@selector(scrollToCell:) withObject:path afterDelay:0];
//}

-(void) scrollToCell:(NSIndexPath*) path {
    [_tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark -textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(CustomField *)textField{
    textField.color=COLOR_SKYBLUE;
    [self addTapGestureRecognizer];
    //将输入的部分滚动到顶部  以免被键盘遮挡
    NSIndexPath* path = [NSIndexPath indexPathForRow:0 inSection:2];
    [self performSelector:@selector(scrollToCell:) withObject:path afterDelay:0];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(CustomField *)textField{
    textField.color=[UIColor lightGrayColor];
    [self removeTapGestureRecognizer];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (string.length == 0) return YES;
    
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    //第一个不允许输入小数点
    if (textField.text.length==0&&[string isEqualToString:@"."]) {
        return NO;
    }
    //不允许出啊先两个小数点
    if ([textField.text containsString:@"."]&&[string isEqualToString:@"."]) {
        return NO;
    }
    NSInteger count=6;
    //有小数点则限制为4为  整数为2位
    if ([textField.text containsString:@"."]||[string isEqualToString:@"."]) {
        count=8;
    }
    if (existedLength - selectedLength + replaceLength > count) {
        return NO;
    }
    
    return YES;
}



#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return _titleArr.count;
    }else if (section==1){
        return _planArr.count;
    }else{
        return 3;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        //申请人员  公出天数  公出人员
        if (indexPath.row==0||indexPath.row==3) {
            NSString *cellID=@"DutyBasicTableViewCell";
            DutyBasicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell=[[DutyBasicTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                //重新设置
                if (indexPath.row==5) {
                    cell.messageLabel.numberOfLines=0;
                    cell.messageLabel.y=0;
                    cell.messageLabel.height=50;
                }
            }
            // 因为考虑到cell复用问题 所以写到外面
            if (indexPath.row==3) {
                _personLabel=cell.messageLabel;
            }
            cell.myTitleLabel.text=_titleArr[indexPath.row];
            cell.messageLabel.text=_messageArr[indexPath.row];
            return cell;
            //开始 结束时间 共处地点
        }else{
            NSString *cellID=@"DutyBasicTableViewCell1";
            DutyBasicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell=[[DutyBasicTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                if (indexPath.row==1) {
                    [cell.signButton addTarget:self action:@selector(signButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                }
            }
            cell.myTitleLabel.text=_titleArr[indexPath.row];
            cell.messageLabel.text=_messageArr[indexPath.row];
            
            if (indexPath.row==1) {
                self.beginSignButton=cell.signButton;
                self.beginTitleLabel=cell.myTitleLabel;
            }else if (indexPath.row==2){
                self.endSignButton=cell.signButton;
                self.endTitleLabel=cell.myTitleLabel;
            }
            //开始时间  结束时间
            cell.arrowImageView.hidden=NO;
            if ([cell.messageLabel.text isEqualToString:@"点击选择"]) {
                cell.messageLabel.textColor=[UIColor lightGrayColor];
            }else{
                cell.messageLabel.textColor=[UIColor blackColor];
            }
            return cell;
        }
    }else if (indexPath.section==2){
        //就餐费用
        if (indexPath.row==0) {
            NSString *cellID=@"DutyBasicTableViewCell2";
            DutyBasicTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell=[[DutyBasicTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                
                _eatTextField=[[CustomField alloc]initWithFrame:CGRectMake(cell.myTitleLabel.x+cell.myTitleLabel.width+10, cell.myTitleLabel.y, 70, cell.myTitleLabel.height)];
                _eatTextField.delegate=self;
                _eatTextField.textAlignment=NSTextAlignmentCenter;
                _eatTextField.textColor=[UIColor blackColor];
                _eatTextField.keyboardType=UIKeyboardTypeNumberPad;
                [cell.contentView addSubview:_eatTextField];
                
                cell.messageLabel.text=@"元";
                cell.messageLabel.x=_eatTextField.x+_eatTextField.width;
            }
            cell.myTitleLabel.text=@"就餐费用 :";
            self.eatExpenseTitleLabel=cell.myTitleLabel;
            //            self.eatExpenseLabel=cell.messageLabel;
            return cell;
            //带出物品和备注
        }else{
            NSString *cellID=@"ReasonTextTableViewCell2";
            ReasonTextTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell=[[ReasonTextTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID title:indexPath.row==1?@" 带回物品及资料 :":@" 汇报说明 :" noticeStr:indexPath.row==1?@"请输入带回物品和资料~":@"请输入~"];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                //添加分割线
                UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 99, IPHONE_WIDTH, 1)];
                line.backgroundColor=BACKCOLOR_GRAY;
                [cell.contentView addSubview:line];
                cell.reasonTextView.tag=indexPath.row+1000*(indexPath.section+1);
                cell.reasonTextView.delegate=self;
            }
            //如果是历史数据
            if (self.goOutInfoModel) {
                if (indexPath.row==1) {
                    if (self.goOutInfoModel.takeTools.length>0) {
                        cell.reasonTextView.text=self.goOutInfoModel.takeTools;
                        cell.reasonTextView.textColor=[UIColor blackColor];
                    }
                }else{
                    if (self.goOutInfoModel.remark.length>0) {
                        cell.reasonTextView.text=self.goOutInfoModel.remark;
                        cell.reasonTextView.textColor=[UIColor blackColor];
                    }
                }
            }
            if (indexPath.row==1) {
                self.materialTextView=cell.reasonTextView;
                self.materialTitleLabel=cell.myTitleLabel;
            }else{
                self.remarksTextView=cell.reasonTextView;
                self.remarksTitleLabel=cell.myTitleLabel;
            }
            
            return cell;
        }
    }else{
        //行程
        NSString *cellID=@"GoOutPlanTableViewCell";
        GoOutPlanTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell=[[GoOutPlanTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        AddPlanModel *model=_planArr[indexPath.row];
        cell.startMessage.text=model.startStr;
        cell.endMessage.text=model.endStr;
        cell.meansMessage.text=model.meansStr;
        cell.spendMessage.text=model.spendStr;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.reasonTextView resignFirstResponder];
    
    //如果是第一分区
    if (indexPath.section==0) {
        if (indexPath.row==1||indexPath.row==2){
            NSString *dateStr=nil;
            if (indexPath.row==1) {
                if (self.beginStr) {
                    dateStr=self.beginStr;
                }
            }
            if (indexPath.row==2) {
                if (self.endStr) {
                    dateStr=self.endStr;
                }
            }
            DatePickerView *datePickerView=[[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)nowDateStr:dateStr];
            __weak NSMutableArray *myMessageArr=_messageArr;
            __weak UITableView *myTableView=_tableView;
            __weak DutyParentsViewController *mySelf=self;
            datePickerView.sureBlock=^(NSString *timeStr){
                if (indexPath.row==1) {
                    //如果是选择开始时间
                    //先判断有没有结束时间,如果有要进行比对
                    if (mySelf.endStr) {
                        if (![mySelf compareOneTime:timeStr withAnotherTime:mySelf.endStr]) {
                            [LZXHelper postMessageWithText:@"公出结束时间应该在公出开始时间之后!" View:mySelf.view];
                        }
//                        [mySelf getVacateDaysOnlyRequest];
                    }
                    //比现在的时间晚
                    mySelf.beginStr=[timeStr copy];
                    
                    [mySelf setLabelBorderColorWithLabel:mySelf.beginTitleLabel color:[UIColor clearColor]];
                    [myMessageArr replaceObjectAtIndex:indexPath.row withObject:timeStr];
                    [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//                    [mySelf getTimeControlRequestWithBeginTime:[timeStr copy]endTime:nil type:@"Begin"];
                }else{
                    //点击结束时间
                    mySelf.endStr=[timeStr copy];
                    [mySelf setLabelBorderColorWithLabel:mySelf.endTitleLabel color:[UIColor clearColor]];
                    [myMessageArr replaceObjectAtIndex:indexPath.row withObject:timeStr];
                    [myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//                    [mySelf getVacateDaysOnlyRequest];
//                    [mySelf getTimeControlRequestWithBeginTime:mySelf.beginStr endTime:[timeStr copy] type:@"End"];
                }
            };
            [[[UIApplication sharedApplication].delegate window] addSubview:datePickerView];
            //公出地点
        }else if (indexPath.row==3){
            
            if (_personListModel) {
                [self postSelectPersonController:_personListModel];
            }else{
                [self getDepartPersonListRequest];
            }
        }
        //就餐费用
    }else if(indexPath.section==2){
        
        //行程计划
    }else{
        
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //行程计划
    if (section==1) {
        UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 50)];
        
        
        UILabel *myTitleLabel=[MyControl creatLabelWithFrame:CGRectMake(8, 10, 80, 30) text:@""];
        myTitleLabel.textAlignment=NSTextAlignmentCenter;
        myTitleLabel.layer.masksToBounds=YES;
        myTitleLabel.layer.cornerRadius=5;
        myTitleLabel.text=@"实际行程 :";
        [backView addSubview:myTitleLabel];
        
        //如果有计划 则需要计算花费总金额
        if (self.planArr.count>0) {
            NSInteger spend=0;
            for (AddPlanModel *model in _planArr) {
                spend+=[model.spendStr integerValue];
            }
            UILabel *messageLabel=[MyControl creatLabelWithFrame:CGRectMake(myTitleLabel.x+myTitleLabel.width+5, 15, IPHONE_WIDTH-(myTitleLabel.x+myTitleLabel.width)-10-50, 20) text:@""];
            messageLabel.textColor=[UIColor blackColor];
            messageLabel.textAlignment=NSTextAlignmentRight;
            messageLabel.text=[NSString stringWithFormat:@"总金额：%ld元",spend];
            //_messageLabel.font=FONT_17;
            [backView addSubview:messageLabel];
        }
        
        UIButton *signButton=[UIButton buttonWithType:UIButtonTypeCustom];
        signButton.frame=CGRectMake(0, 0, IPHONE_WIDTH, 50);
        [signButton addTarget:self action:@selector(signButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [backView addSubview:signButton];
        
        UIImageView *arrowImageView=[MyControl creatImageViewWithFrame:CGRectMake(IPHONE_WIDTH-50, 18, 8, 14) imageName:@"k_ic_jt@2x"];
        [backView addSubview:arrowImageView];
        //添加分割线
        UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 49, IPHONE_WIDTH, 1)];
        line.backgroundColor=BACKCOLOR_GRAY;
        [backView addSubview:line];
        return backView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0){
        //输入框高度为100
        return 50;
    }else if (indexPath.section==2){
        //输入框高度为100
        if (indexPath.row==1||indexPath.row==2) {
            return 100;
        }
    }else if (indexPath.section==1){
        return 90;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //设置行程计划的高度
    if (section==1) {
        return 50;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

#pragma mark -行程计划点击

- (void)signButtonClick{
    //跳转到增加委托人页面
    AddPlanViewController *person=[AddPlanViewController new];
    person.dataArr=self.planArr;
    __weak UITableView *myTableView=_tableView;
    __weak DutyGoBackViewController *mySelf=self;
    //增加委托人回调函数 并刷新列表
    person.myBlock=^(NSMutableArray *dataArr){
        mySelf.planArr=dataArr;
        [myTableView reloadSections:[NSIndexSet indexSetWithIndex:1]  withRowAnimation:UITableViewRowAnimationNone];
    };
    [self.navigationController pushViewController:person animated:YES];
}

#pragma mark -获取人员列表请求
- (void)getDepartPersonListRequest{
    NSDictionary *dict=@{
                         @"departName":[LZXHelper getUserDepartName]?[LZXHelper getUserDepartName]:@"",
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getDepartPersonList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        _personListModel=[[DepartPersonListModel alloc]initWithResponse:responseObject];
        if ([_personListModel.code isEqualToString:@"200"]) {
            [self postSelectPersonController:_personListModel];
            
        }else if([_personListModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_personListModel.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}

#pragma mark -公出汇报
- (void)postBusinessReportInfoRequest{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *timeStr=[formatter stringFromDate:[NSDate date]];
    
    NSString *empId=[NSString stringWithFormat:@"|%@|",[LZXHelper getSessionID]];
    
    //如果有计划 则需要计算花费总金额
    NSString *mealsCost=@"0";
    if (self.planArr.count>0) {
        NSInteger spend=0;
        for (AddPlanModel *model in _planArr) {
            spend+=[model.spendStr integerValue];
        }
        mealsCost=[NSString stringWithFormat:@"%ld",spend];
    }
    
    //添加照片信息
    NSMutableArray *imageInfoArr=[NSMutableArray new];
    for (int i=0; i<_imageModel.dataArr.count; i++) {
        NSMutableDictionary *dict=[NSMutableDictionary new];
        UserHeadImageModel *model=_imageModel.dataArr[0];
        [dict setObject:model.picPath forKey:@"picPath"];
        [dict setObject:model.picName forKey:@"picName"];
        [imageInfoArr addObject:dict];
    }
    
    NSDictionary *dict=@{
                         @"itsState":@"0",
                         @"applyTime":timeStr?timeStr:@"",
                         @"empIds":empId?empId:@"",
                         @"businessEnd":self.endStr?self.endStr:@"",
                         @"businessStart":self.beginStr?self.beginStr:@"",
                         @"id":self.vacateBillId?self.vacateBillId:@"",
                         @"mealCost":_eatTextField.text?_eatTextField.text:@"",
                         @"trafficCost":mealsCost,
                         @"trafficType":@"",
                         @"infoId":self.infoId?self.infoId:@"",
                         @"obAddress":self.goOutInfoModel.obAddress?self.goOutInfoModel.obAddress:@"",
                         @"optionType":self.optionType?self.optionType:@"",
                         @"serviceTime":self.serviceTime?self.serviceTime:timeStr,
                         @"explanationDetail":[self.remarksTextView.text isEqualToString:@"请输入带回物品和资料~"]?@"":self.remarksTextView.text,
                         @"bringTools":[self.materialTextView.text isEqualToString:@"请输入~"]?@"":self.materialTextView.text,
                         @"obAddress_x":self.placeX?self.placeX:@"",
                         @"obAddress_y":self.placeY?self.placeY:@"",
                         @"voiceName":@"",
                         @"voicePath":@"",
                         };
    NSMutableDictionary *newDict=[NSMutableDictionary dictionaryWithDictionary:dict];
    NSMutableArray *listArr=[NSMutableArray new];
    for (AddPlanModel *model in _planArr) {
        NSDictionary *modelDict=@{
                                  @"fromAddr":model.startStr?model.startStr:@"",
                                  @"price":model.spendStr?model.spendStr:@"",
                                  @"toAddr":model.endStr?model.endStr:@"",
                                  @"tripId":model.keywordId?model.keywordId:@"",
                                  @"tripName":model.meansStr?model.meansStr:@"",
                                  };
        [listArr addObject:modelDict];
    }
    [newDict setObject:listArr forKey:@"traficList"];
    [newDict setObject:imageInfoArr forKey:@"picList"];
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    // __weak AddressBookViewController *mySelf=self;
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:postBusinessReportInfo soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        BasicModel *model=[[BasicModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"200"]) {
            [LZXHelper postMessageWithText:model.msg View:[[UIApplication sharedApplication].delegate window]];
            if (self.vacateBillId) {
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[MyJobListViewController class]]) {
                        [self.navigationController popToViewController:controller animated:YES];
                    }
                }
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else if([model.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:model.msg View:[[UIApplication sharedApplication].delegate window]];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
}


#pragma mark -进入人员选择页面
- (void)postSelectPersonController:(DepartPersonListModel *)model{
    SelectOvertimePersonViewController *overtime=[SelectOvertimePersonViewController new];
    overtime.personListModel=model;
    __weak DutyGoBackViewController *mySelf=self;
    overtime.myBlock=^(){
        //这里需要将参数传过去
        NSString *personMsg=_messageArr[3];
        //拼接字符串
        for (DepartPersonListModel *model in self.personListModel.dataArr) {
            if (model.isSelect) {
                personMsg=[personMsg stringByAppendingString:[NSString stringWithFormat:@",%@",model.empName]];
            }
        }
        mySelf.personLabel.text=personMsg;
    };
    [self.navigationController pushViewController:overtime animated:YES];
}

#pragma mark -查看页面公出信息
- (void)getVacateInfoRequestWithVacateBillId:(NSString *)vacateBillId{
    
    NSDictionary *dict=@{
                         @"vacateBillId":vacateBillId?vacateBillId:@"",
                         @"businessCode":self.businessCode?self.businessCode:@"",
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    //[LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getBusinessInformationInfo soapBody:soap success:^(id responseObject) {
        //[LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        BasicModel *model=[[BasicModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"200"]) {
            [self getVacateInfoRequestSuccess:responseObject];
        }else if([model.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }
    } failure:^(NSError *error) {
        //[LZXHelper hideLoadViewWithView:self.view];
    }];
}

#pragma mark -上传照片
- (void)uploadPhotoImage{
    //    if (!_image) {
    //        return;
    //    }
    //    [self.view addSubview:self.centerIndicator];
    //    [self.centerIndicator startAnimating];
    //    NSString *token=[[NSUserDefaults standardUserDefaults]objectForKey:@"Token"];
    //    NSIndexPath * selectedIndex = [_tableView indexPathForSelectedRow];
    //    MyInfoHeadViewCell * cell = [_tableView cellForRowAtIndexPath:selectedIndex];
    //    //NSString * sourcePath = [MyControl storeImagePath];
    //    PersonCenterViewController * pc = (PersonCenterViewController *)self.PersonVC;
    //
    
    NSMutableDictionary *picList=[NSMutableDictionary new];
    NSMutableArray *imageArr=[NSMutableArray new];
    
    for (int i=0; i<_photoArr.count; i++) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
        //以时间为照片命名
        NSString *timestamp = [[formatter stringFromDate:[NSDate date]] stringByAppendingString:@".jpg"];
        
        UIImage *image=_photoArr[i];
        NSData *date = UIImageJPEGRepresentation(image, 0.5);
        NSString * imageStr = [date base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSDictionary *dict=@{
                             @"picName":timestamp,
                             @"picBase":imageStr,
                             @"picType":@"gongChu",
                             };
        
        [imageArr addObject:dict];
    }
    
    [picList setObject:imageArr forKey:@"picList"];
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:picList options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:uploadPicInfo soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        //解析数据并保存用户数据
        //NSLog(@"%@",responseObject[@"msg"]);
        _imageModel=[[UserHeadImageModel alloc]initWithResponse:responseObject];
        if ([_imageModel.code isEqualToString:@"200"]) {
            [LZXHelper postAlertViewControllerWithTitle:@"确定要提交吗?" message:nil cancelButtonTitle:@"取消" otherButtonTitle:@"确定" cancelEvent:^{
                
            } otherEvent:^{
                [self postBusinessReportInfoRequest];
            } viewController:self];
        }else if([_imageModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_imageModel.msg View:self.view];
        }
        
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:self.view];
    }];
    
}

#pragma mark -页面信息请求成功
- (void)getVacateInfoRequestSuccess:(id)responseObject{
    //解析数据
    self.goOutInfoModel=[[GoOutInfoModel alloc]initWithResponse:responseObject];
    //设置数据
    self.beginStr=self.goOutInfoModel.startTime;
    self.endStr=self.goOutInfoModel.endTime;
    self.placeX=self.goOutInfoModel.placeX;
    self.placeY=self.goOutInfoModel.placeY;
    self.taskId=self.infoModel.TaskID;
   //带回物品
    if (self.goOutInfoModel.remark.length>0) {
        self.remarksTextView.text=self.goOutInfoModel.remark;
        self.remarksTextView.textColor=[UIColor blackColor];
    }
    //汇报说明
    if (self.goOutInfoModel.takeTools.length>0) {
        self.materialTextView.text=self.goOutInfoModel.takeTools;
        self.materialTextView.textColor=[UIColor blackColor];
    }
    //替换数据
    _messageArr=[NSMutableArray arrayWithArray:@[[LZXHelper getUserName],self.beginStr?self.beginStr:@"点击选择",self.endStr?self.endStr:@"点击选择",self.goOutInfoModel.empName?self.goOutInfoModel.empName:[LZXHelper getUserName]]];
    //保存委托人
    if (self.goOutInfoModel.trafficList.count>0) {
        for (int i=0; i<self.goOutInfoModel.trafficList.count; i++) {
            GoOutInfoModel *model=self.goOutInfoModel.trafficList[i];
            AddPlanModel *newModel=[AddPlanModel new];
            newModel.startStr=model.fromAddr;
            newModel.endStr=model.toAddr;
            newModel.meansStr=model.tripName;
            newModel.spendStr=[NSString stringWithFormat:@"%.1f元",[model.price floatValue]];
            newModel.keywordId=model.tripId;
            [self.planArr addObject:newModel];
        }
    }
    [_tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
